<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="大纲名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入大纲名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:outline:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:outline:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:outline:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:outline:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outlineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="大纲名称" align="center" prop="name" />
      <el-table-column label="使用模型" align="center" prop="useModel" />
<!--      <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:outline:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:outline:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章大纲对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="大纲名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入大纲名称" />
        </el-form-item>

        <el-form-item label="算法模型" prop="useModel">
          <el-select
            v-model="form.useModel"
            placeholder="使用模型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.gpt_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="大纲内容" prop="contentOutline">-->
<!--          <el-input v-model="form.contentOutline" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->


        <div v-for="(item, index) in form.outlineArray" :key="index" style="background-color:#f2f5f9;margin: 10px;"   >
          <el-form  :model="form.outlineArray[index]" :rules="rules" label-width="120px" style="padding: 15px;">
            <!--    动态产生重复表单项      -->
            <el-row>
              <el-col :span="16">
                <el-form-item label="大纲标题" prop="title">
                  <el-input v-model="item.title" @input="changeVal($event)" placeholder="请输入大纲名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="生成要求" prop="genPrompts">
                  <el-input v-model="item.genPrompts"   @input="changeVal($event)"  placeholder="请输入生成要求" />
<!--                  <el-input v-model="form.genPrompts" :autosize="{ minRows: 3, maxRows: 5}"  type="textarea" placeholder="请输入生成要求" />-->
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="必须包含" prop="mustHas">
                <el-switch
                  v-model="item.mustHas"
                  active-color="#13ce66"
                  @input="changeVal($event)"
                  inactive-color="#dad6d6">
                </el-switch>

                </el-form-item>

              </el-col>
            </el-row>


            <el-row >
              <el-button  @click="delItem(index)" type="danger" plain icon="el-icon-delete" size="mini" style="float: right;">删除本条</el-button>
            </el-row>
          </el-form>
        </div>
        <el-button @click="addItem" type="primary" plain  icon="el-icon-plus" size="mini" style="margin-bottom: 65px;">增加大纲</el-button>


        <el-form-item label="使用条数" prop="useNum">
<!--          <el-input v-model="form.useNum" placeholder="请输入使用大纲条数，随机模式" />-->
<!--          <el-input-number v-model="num" @change="handleChange" :min="1" :max="10" label="描述文字"></el-input-number>-->
          <el-input-number v-model='form.useNum' :min="1" :max="30" label="条数，随机模式"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutline, getOutline, delOutline, addOutline, updateOutline } from "@/api/article/outline";

export default {
  name: "Outline",
  dicts: ['gpt_model'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章大纲表格数据
      outlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      // 表单参数
      form: {
        outlineArray:JSON.parse('[{"title":"","genPrompts":"","mustHas":false}]')
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文章大纲列表 */
    getList() {
      this.loading = true;
      listOutline(this.queryParams).then(response => {
        this.outlineList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
    },

    changeVal(e){
         this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        outlineArray: JSON.parse('[{"title":"","genPrompts":"","mustHas":false}]'),
        status: null,
        createTime: null,
        createBy: null,
        remark: null,
        useNum: null
      };
      this.resetForm("form");
    },
    /**  点击新增后增加新的项目  **/
    addItem(){
      // console.log(this.form.contentOutline);
      this.form.outlineArray.push({"title":"","genPrompts":"","mustHas":false});
    },
    /**  点击按钮删除动态添加的表单  **/
    delItem(index){
      this.form.outlineArray.splice(index,1);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章大纲";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const id = row.id || this.ids
      getOutline(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章大纲";

        this.form.outlineArray= JSON.parse(this.form.contentOutline);
        // this.form.outlineArray = JSON.parse(JSON.stringify(this.form.contentOutline));
        this.form.outlineArray.map((item, i) => {
          this.$set(this.form, 'title'+(i+1), item.title)
          this.$set(this.form, 'genPrompts'+(i+1), item.genPrompts)
          this.$set(this.form, 'mustHas'+(i+1), item.mustHas)
        })
          // [{"title":"","genPrompts":"","mustHas":false}]
        //
        // this.form.outlineArray.forEach(item =>{
        //    console.log(item)
        //   this.$set(this.form, 'title', item.title)
        //   this.$set(this.form, 'genPrompts', item.genPrompts)
        // })
        // this.$set(this.ruleForm, 'finishTime', time)

      });
    },
    /** 提交按钮 */
    submitForm() {
      let fa = this.form.outlineArray;
      let newOutlineArray = [];
      for(var i =0;i<fa.length;i++){
        let ey = fa[i];
        ey.index = i;
        newOutlineArray.push(ey);
      }
      const jsonData = JSON.stringify(newOutlineArray);
      // this.formData = JSON.parse(JSON.stringify(this.form.outlineArray));

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.contentOutline = jsonData;
          // console.log(this.form.contentOutline)
          if (this.form.id != null) {
            updateOutline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文章大纲编号为"' + ids + '"的数据项？').then(function() {
        return delOutline(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/outline/export', {
        ...this.queryParams
      }, `outline_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
